﻿using IM.Easy.Api.AccountManage;
using IM.Easy.SystemServices.IServices;
using IM.Easy.SystemServices.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;

namespace IM.Easy.Api.Hubs
{

    /// <summary>
    /// SignalR 在线用户管理服务，处理用户的连接、断开以及消息发送。
    /// </summary>
    public class UserHub : Hub
    {
        private readonly IOnlineService _userManager;

        /// <summary>
        /// 初始化 <see cref="UserHub"/> 实例。
        /// </summary>
        /// <param name="userManager">在线用户管理服务。</param>
        public UserHub(IOnlineService userManager)
        {
            _userManager = userManager;
        }

        /// <summary>
        /// 用户连接时调用的方法。
        /// </summary>
        /// <returns>异步任务。</returns>
        public override async Task OnConnectedAsync()
        {
            var userId = Context.User?.FindFirst(ClaimTypes.PrimarySid)?.Value;
            var nickName = Context.User?.FindFirst(ClaimTypes.Name)?.Value;
            if (!string.IsNullOrEmpty(userId))
            {
                _userManager.Online(userId, Context.ConnectionId);
                await Clients.Others.SendAsync("UserConnected", nickName);
            }
            base.OnConnectedAsync();
        }

        /// <summary>
        /// 用户断开连接时调用的方法。
        /// </summary>
        /// <param name="exception">连接断开时的异常信息，如果存在。</param>
        /// <returns>异步任务。</returns>
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            var userId = _userManager.GetUserIdByConnectionId(Context.ConnectionId);
            if (!string.IsNullOrEmpty(userId))
            {
                var user = _userManager.Offline(Context.ConnectionId);
                await Clients.Others.SendAsync("UserDisconnected", user?.NickName);
            }
            await base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 向指定用户发送消息。
        /// </summary>
        /// <param name="userId">目标用户的唯一标识。</param>
        /// <param name="message">发送的消息内容。</param>
        /// <returns>异步任务。</returns>
        public async Task SendMessageToUser(string userId, string message)
        {
            var connectionId = _userManager.GetConnectionIdByUserId(userId);
            if (connectionId != null)
            {
                await Clients.Client(connectionId).SendAsync("ReceiveMessage", message);
            }
        }

        /// <summary>
        /// 用户登录后调用的 SignalR 方法，用于标记用户登录
        /// </summary>
        /// <returns></returns>
        public async Task OnSignIn()
        {
            //var user = _userManager.GetUserIdByConnectionId(Context.ConnectionId);
            var user = Context.User?.FindFirst(ClaimTypes.PrimarySid)?.Value;
            // 通知其他用户有用户登录
            await Clients.Others.SendAsync("UserSignOn", user);
            //if (!string.IsNullOrEmpty(user))
            //{
            //    _userManager.AddUser(user, Context.ConnectionId);

            //    // 通知其他用户有用户登录
            //    await Clients.Others.SendAsync("UserSignOn", user);
            //}
        }

    }


}
